'use client';

import { useQuery } from '@tanstack/react-query';
import { queryOauthClientApis } from '@/services/api';
import { useContext, useState } from 'react';
import type { IOauthClientApi } from '@/interfaces';
import classNames from 'classnames';
import {
  OAUTH_CLIENT_API_REVIEW_STATE_KEY,
  OAUTH_CLIENT_API_TYPE_KEY,
} from '@/lib/constant';
import Alert from '@/app/[locale]/alert/alert';
import useToast from '@/hooks/useToast';
import AlertLoad from '@/app/[locale]/alert/load';
import { OauthClientAdminContext } from '@/contexts/admin/oauth/client';
import OauthClientInterfaceDetailsAdminPage from '@/app/[locale]/admin/oauth/client/interface/detail';
import UpdateOauthClientInterfaceAdminPage from '@/app/[locale]/admin/oauth/client/interface/update';

export default function OauthClientInterfaceAdminPage(this: any) {
  const [currentItemId, setCurrentItemId] = useState<number>();
  const { show } = useToast();
  const context = useContext(OauthClientAdminContext);
  const [detailItem, setDetailItem] = useState<IOauthClientApi>();
  const [updateItem, setUpdateItem] = useState<IOauthClientApi>();

  const queryOauthClientApisByIdQuery = useQuery(
    ['/oauth', '/clients', '/apis', { cid: context.detailItem?.id }],
    async (context) => {
      try {
        return (await queryOauthClientApis({
          query: (context.queryKey[3] || {}) as {},
        })) as IOauthClientApi[];
      } catch (e) {
        show({
          type: 'DANGER',
          message: e,
        });
        throw e;
      }
    },
  );

  function onClickDetail(item: IOauthClientApi) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  function onClickUpdate(item: IOauthClientApi) {
    setUpdateItem(item);
  }

  if (queryOauthClientApisByIdQuery.data) {
    const data = queryOauthClientApisByIdQuery.data;

    return (
      <OauthClientAdminContext.Provider
        value={{
          ...context,
          oauthClientApiDetailItem: detailItem,
          oauthClientApiUpdateItem: updateItem,
          setOauthClientApiDetailItem: setDetailItem,
          setOauthClientApiUpdateItem: setUpdateItem,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="vstack gap-4">
              <div className="row">
                <div className="col">
                  <div className="card">
                    <div className="card-header bg-transparent text-muted">
                      <i className="bi bi-info-square me-2"></i>
                      开放认证客户端接口申请
                    </div>
                    <div className="card-body">
                      <div className="table-responsive">
                        <table className="table table-hover align-middle">
                          <thead>
                            <tr className="text-nowrap">
                              <th scope="col" className="w-10">
                                名称
                              </th>
                              <th scope="col" className="w-10">
                                概述
                              </th>
                              <th scope="col" className="w-10">
                                分类
                              </th>
                              <th scope="col" className="w-10">
                                每日调用量&nbsp;/&nbsp;上限
                              </th>
                              <th scope="col" className="w-10">
                                类型
                              </th>
                              <th scope="col" className="w-10">
                                审核状态
                              </th>
                              <th scope="col" className="w-10">
                                创建
                              </th>
                              <th scope="col" className="w-10"></th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.map((item) => {
                              return (
                                <tr
                                  key={item.id}
                                  className={classNames('text-nowrap', {
                                    'table-active': currentItemId === item.id,
                                  })}
                                >
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.name}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.overview}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.category}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    <span>{item.dailyCalls || 0}</span>
                                    <span>&nbsp;/&nbsp;</span>
                                    <span>
                                      {item.upperLimit === 0
                                        ? '无上限'
                                        : item.upperLimit}
                                    </span>
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {OAUTH_CLIENT_API_TYPE_KEY[item.type]}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.type === 'DEFAULT' ||
                                    item.reviewState === 'SUCCESSFUL' ? (
                                      <i
                                        className="bi bi-patch-check-fill me-2 text-success fs-5"
                                        title="通过"
                                      ></i>
                                    ) : (
                                      <span>
                                        {
                                          OAUTH_CLIENT_API_REVIEW_STATE_KEY[
                                            item.reviewState!
                                          ]
                                        }
                                      </span>
                                    )}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.createdOn}
                                  </td>
                                  <td>
                                    {item.type === 'REQUIRED' &&
                                      item.reviewState && (
                                        <button
                                          onClick={onClickUpdate.bind(
                                            this,
                                            item,
                                          )}
                                          className="btn btn-sm btn-light"
                                          type="button"
                                        >
                                          <i className="bi bi-pencil me-2"></i>
                                          修改
                                        </button>
                                      )}
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>

                      {data.length === 0 && (
                        <Alert message="暂无开放认证客户端接口" />
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {detailItem && <OauthClientInterfaceDetailsAdminPage />}

              {updateItem && <UpdateOauthClientInterfaceAdminPage />}
            </div>
          </div>
        </div>
      </OauthClientAdminContext.Provider>
    );
  }

  if (queryOauthClientApisByIdQuery.error) {
    return <Alert type="error" message={queryOauthClientApisByIdQuery.error} />;
  }

  return <AlertLoad />;
}
